<?php

namespace app\controller;

use app\model\Se5Device;
use app\model\Se5Event;
use fast\Http;
use think\facade\Db;
use think\facade\Log;

class SefiveEvent extends BackendController {
    protected $model = null;
    protected $noNeedLogin = ['http'];
    protected $noNeedRight=['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\model\Se5Event();
    }

    public function http(){

        $now_time=date("Y-m-d H:i:s");
        $log_id=md5($now_time).rand(1000,9999);
        $input=file_get_contents('php://input');
        //Log::info($log_id.'se5平台推送信息：'.$input);
        $temp=json_decode($input,true);
        if(!$temp){
            return 'error';
        }

        if(isset($temp['Metadata'])){
            $FullImage=$temp['Metadata']['FullImage'];
            //数据推送
            unset($temp['Metadata']['Image']);
            unset($temp['Metadata']['FullImage']);
            Log::info($log_id.'se5平台推送信息：'.json_encode($temp));
            $max_num=config('capture.max_se5_num');
            $_se5=new Se5Event();
            Db::startTrans();
            try {
                $now_num = $_se5->count();
                //超过条数则删一条
                if ($now_num >= $max_num) {
                    $first = $_se5->order('id', 'asc')->find();
                    file_unlink($first['file_path'].$first['id'].'_face.jpg');
                    file_unlink($first['file_path'].$first['id'].'_bg.jpg');
                    $_se5->delete($first['id']);
                }
                unset($temp['ID']);
                $file_path=config('capture.se5_path').'/'.date('Ym').'/'.date('d').'/';
                //$temp['Rect']=json_encode($temp['Rect']);
                $temp['DeviceID']=$temp['Metadata']['DeviceID'];
                $temp['Workflow']=$temp['Metadata']['Workflow'];
                $temp['WorkflowName']=$temp['Metadata']['WorkflowName'];
                $temp['ChannelName']=$temp['Metadata']['ChannelName'];
                $temp['Timestamp']=$temp['Metadata']['Timestamp'];
                $temp['Rect']=json_encode($temp['Metadata']['Rect']);
                $rect=$temp['Metadata']['Rect'];
                unset($temp['Metadata']);
                $temp['file_path']=$file_path;
                $_se5->save($temp);
                //save_base_img($_se5->id.'_face',$image,$file_path);
                save_base_img($_se5->id.'_bg',$FullImage,$file_path);
                Db::commit();
                $temp['id']=$_se5->id;
                $push_data['msg_type'] = 'se5_event';
                $temp['Rect']=$rect;
                $push_data['data'] = $temp;
                Http::post('http://127.0.0.1:9503', ['content' => json_encode($push_data)]);
            }catch (\Exception $e){
                Db::rollback();
                Log::error($e->getMessage());
                Log::error($e->getTraceAsString());
            }
            //来自特殊设备的加入face表
            /*$device_ids=config('capture.se5_face');
            //$device_id=$temp['DeviceID'].'-'.$temp['Channel'];
            $device_id=$temp['DeviceID'];
            if(in_array($device_id,$device_ids)&&$temp['MetaType']===0){
                Log::info($log_id.'se5平台推送face队列');
                $face['DeviceID']=$device_id;
                $face['SourceID']=$face['DeviceID'];

                $images[0]['Data']=$image;
                $images[0]['ImageID']=$face['DeviceID'].'0';
                $images[1]['Data']=$FullImage;
                $images[1]['ImageID']=$face['DeviceID'].'1';
                $face['SubImageList']['SubImageInfoObject'][0]=$images[1];
                $face['SubImageList']['SubImageInfoObject'][1]=$images[0];
                //$face['feature']=$temp['Feature'];
                $faces['FaceListObject']['FaceObject'][]=$face;
                $faces['feature']=$temp['Feature'];
                $content=json_encode($faces);
                $job_data = [];
                $job_data["ts"] = time();
                $job_data["bizid"] = uniqid();
                $job_data["params"] =$content;
                $job_data["log_id"]=$log_id;
                $is_pushed=Queue::push(Capture::class,$job_data,'http_list');
            }*/
        }else{
            //心跳
            Log::debug('se5平台心跳：'.$input);
            $_se5_device=new Se5Device();
            $temp['HostDisk']=json_encode($temp['HostDisk']);
            $temp['HostMemory']=json_encode($temp['HostMemory']);
            $temp['Content']=json_encode($temp['Content']);
            $temp['last_time']=date("Y-m-d H:i:s");
            $_se5_device->replace()->save($temp);
            //$this->success("不是人脸过滤：".$temp['MetaType']);
        }
    }

    public function index_group($start_time,$end_time) {
        $_se5=new Se5Event();
        $lists=$_se5->whereBetweenTime('Timestamp',$start_time,$end_time)
            ->field('count(*),WarnType')
            ->group('WarnType')
            ->select();
        foreach ($lists as $list){
            $map['warntype'.$list['WarnType']]=$list['count(*)'];
        }
        $this->success('获取成功',$map);
    }

}